﻿# -*- coding utf-8 -*-
#!/usr/bin/python
#-------------------------------------------------------------------------------
# Name:
# Purpose:
#
# Author:      ZWW
#
# Created:     03/05/2016
# Copyright:   (c) ZWW 2016
# Licence:     <your licence>
#-------------------------------------------------------------------------------
import numpy as np
import cv2
from matplotlib import pyplot as plt

refPt = []
cropping = False
image = None

def f1(t):
    return np.exp(-t)*np.cos(2*np.pi*t)

def f2(t):
    return np.sin(2*np.pi*t)*np.cos(3*np.pi*t)

def myplot():
    t = np.arange(0.0,5.0,0.02)

    plt.figure(figsize=(8,7),dpi=98)
    p1 = plt.subplot(211)
    p2 = plt.subplot(212)

    p1.plot(t,f1(t),"g-",label="$f(t)=e^{-t} \cdot \cos (2 \pi t)$")
    p2.plot(t,f2(t),"r-.",label="$g(t)=\sin (2 \pi t) \cos (3 \pi t)$",linewidth=2)

    p1.axis([0.0,5.01,-1.0,1.5])

    p1.set_ylabel("v",fontsize=14)
    p1.set_title("A simple example",fontsize=18)
    p1.grid(True)
    p1.legend()

    p2.axis([0.0,5.01,-1.0,1.5])
    p2.set_ylabel("v",fontsize=14)
    p2.set_xlabel("t",fontsize=14)
    p2.legend()

    plt.show()


def ROI():
    print cv2.useOptimized()
    img = cv2.imread('C:\\Users\\ZWW\\Desktop\\7077.bmp')
    px = img[100,100]
    print px
    blue = img[100,100,0]
    print blue
    print img.shape
    print img.dtype
    img[:,:,2]=0
    cv2.imwrite('notred.png', img)

    img = cv2.imread('C:\\Users\\ZWW\\Desktop\\gray.bmp')
    px = img[100,100]
    print px
    blue = img[100,100,0]
    print blue
    print img.shape
    print img.dtype
    ball = img[2300:2600,550:850]
    img[100:400,100:400] = ball
    cv2.imwrite('gray.png', img)

def colorChg():
    flags = [i for i in dir(cv2) if i.startswith('COLOR_')]
    print flags

def traceBlue():
    cap = cv2.VideoCapture(0)
    while(1):
        ret, frame = cap.read()
        hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)

        lower_blue = np.array([110,50,50])
        upper_blue = np.array([130,255,255])

        lower_red = np.array([0,50,50])
        upper_red = np.array([20,255,255])

        maskBlue = cv2.inRange(hsv, lower_blue, upper_blue)
        maskRed = cv2.inRange(hsv, lower_red, upper_red)
        mask = cv2.bitwise_or(maskBlue, maskRed)
        res = cv2.bitwise_and(frame, frame, mask=mask)
        cv2.imshow('frame', frame)
        cv2.imshow('mask', mask)
        cv2.imshow('res', res)
        k = cv2.waitKey(5)&0xFF
        if k == 27:     #Esc
            break

    cv2.destroyAllWindows()

def resize():
    img=cv2.imread('gray.png')
    print img.shape[:2]
    res = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
    cv2.imwrite('big.png', res)

def move():
    img = cv2.imread('small.png')
    rows,cols = img.shape[:2]
    M = np.array([[1.0,0,100],[0,1.0,50]])
    print M
    dst = cv2.warpAffine(img, M, (0,0))
    cv2.imwrite('test.jpg', dst)

def rotate():
    img = cv2.imread('small.png')
    #cv2.imshow("out", img)
    print img.shape
    rows,cols = img.shape[:2]
    M = cv2.getRotationMatrix2D((cols/2, rows/2), 45, 1)
    print M
    dst = cv2.warpAffine(img, M, (cols,rows))
    print dst.shape
    while(1):
        cv2.imshow('imgs', dst)
        if cv2.waitKey(1) & 0xFF == 27:
            break
    cv2.destroyAllWindows()

def affineTransform():
    img = cv2.imread('small.png')
    rows,cols,ch = img.shape
    pts1=np.float32([[50,50],[200,50],[50,200]])
    pts2=np.float32([[10,100],[200,50],[100,250]])
    M=cv2.getAffineTransform(pts1,pts2)
    dst=cv2.warpAffine(img,M,(cols,rows))
    #plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
    plt.subplot(121)
    plt.imshow(img)
    plt.title('Input')
    plt.subplot(122)
    plt.imshow(dst)
    plt.title('Output')
    plt.show()

def perspectiveTransform():
    img=cv2.imread('gray.png')
    rows,cols,ch=img.shape
    pts1 = np.float32([[56,65],[368,52],[28,387],[389,390]])
    pts2 = np.float32([[0,0],[300,0],[0,300],[300,300]])
    M=cv2.getPerspectiveTransform(pts1,pts2)
    dst=cv2.warpPerspective(img,M,(0,0))
    plt.subplot(121)
    plt.imshow(img)
    plt.title('Input')
    plt.subplot(122)
    plt.imshow(dst)
    plt.title('Output')
    plt.show()

def pyramid():
    img=cv2.imread('gray.png')
    print img.shape
    img1 = cv2.pyrDown(img)
    print img1.shape
    img2 = cv2.pyrUp(img)
    plt.subplot(131),plt.imshow(img,'gray'),plt.title('original')
    plt.subplot(132),plt.imshow(img1,'gray'),plt.title('down')
    plt.subplot(133),plt.imshow(img2,'gray'),plt.title('up')
    plt.show()

def grabcut():
    img=cv2.imread('c.jpg')
    mask=np.zeros(img.shape[:2],np.uint8)

    bgdModel=np.zeros((1,65),np.float64)
    fgdModel=np.zeros((1,65),np.float64)

    rect=(50,50,450,290)
    cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)

    mask2=np.where((mask==2)|(mask==0),0,1).astype('uint8')
    img=img*mask2[:,:,np.newaxis]
    plt.imshow(img),plt.colorbar(),plt.show()

def PatternMatching():
    img = cv2.imread('color.bmp', cv2.IMREAD_GRAYSCALE)
    img2 = img.copy()
    template = cv2.imread('temp.jpg', cv2.IMREAD_GRAYSCALE)
    w, h = template.shape[::-1]
    methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR', 'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']
    for meth in methods:
        img = img2.copy()

        method = eval(meth)
        # Apply template Matching
        res = cv2.matchTemplate(img,template,method)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
        # 使用不同的比较方法，对结果的解释不同
        # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
        if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
            top_left = min_loc
        else:
            top_left = max_loc
        bottom_right = (top_left[0] + w, top_left[1] + h)
        cv2.rectangle(img,top_left, bottom_right, 0, 10)
        plt.subplot(121),plt.imshow(res,cmap = 'gray')
        plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
        plt.subplot(122),plt.imshow(img,cmap = 'gray')
        plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
        plt.suptitle(meth)
        plt.show()
    pass

def click_and_crop(event, x, y, flags, param):
    global refPt, cropping, image

    if event == cv2.EVENT_LBUTTONDOWN:
        refPt = [(x, y)]
        cropping = True
        print "first point: %d %d\n"%(x,y)
    elif event == cv2.EVENT_LBUTTONUP:
        refPt.append((x, y))
        cropping = False

        cv2.rectangle(image, refPt[0], refPt[1], (0, 255, 0), 2)
        cv2.imshow("image", image)
        print refPt[1]
    elif event == cv2.EVENT_MOUSEMOVE and len(refPt) == 1:
        image2 = image.copy()
        ptTemp = (x,y)
        if x != refPt[0][0] and y != refPt[0][1]:
            print ptTemp
            cv2.rectangle(image2, refPt[0], ptTemp, (0, 255, 0), 2)
            cv2.imshow("image", image2)

def picDraw():
    global refPt, cropping, image
    image = cv2.imread("c.jpg")
    #image = cv2.imread("Color.bmp")
    clone = image.copy()
    cv2.namedWindow("image")
    cv2.setMouseCallback("image", click_and_crop)

    while True:
        cv2.imshow("image", image)
        key = cv2.waitKey(1) & 0xFF
        if key == ord("r"):
            image = clone.copy()
        elif key == ord("c"):
            break

    if len(refPt) == 2:
        roi= clone[refPt[0][1]:refPt[1][1], refPt[0][0]:refPt[1][0]]
        cv2.imshow("ROI", roi)
        cv2.waitKey(0)

    cv2.destroyAllWindows()

def calcHist():
    img = cv2.imread('c.jpg', cv2.IMREAD_GRAYSCALE)
    cv2.imshow("girl", img)
    hist = cv2.calcHist([img], [0], None, [255], [0,256])
    print hist
    plt.hist(img.ravel(), 256, [0,256])
    plt.show()
    cv2.destroyAllWindows()

def backproject():
    image = cv2.imread('skin.png', cv2.IMREAD_COLOR)
    #cv2.imshow("image", image)
    gray_plane = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    #cv2.imshow("gray_plane", gray_plane)
    gray_hist = cv2.calcHist([gray_plane], [0], None, [255], [0,256])
    cv2.normalize(gray_hist,gray_hist,0,255,cv2.NORM_MINMAX)
    print gray_hist

    gray_plane2 = cv2.imread('2.jpg', cv2.IMREAD_GRAYSCALE)
    #cv2.imshow('gray_plane2', gray_plane2)
    dst = cv2.calcBackProject([gray_plane2],[0],gray_hist,[0,255],1)
    cv2.imshow('dst', dst)
    cv2.waitKey(0)

def backproject2():
    roi = cv2.imread('skin.png')
    hsv = cv2.cvtColor(roi,cv2.COLOR_BGR2HSV)
    target = cv2.imread('2.jpg')
    hsvt = cv2.cvtColor(target,cv2.COLOR_BGR2HSV)
    # calculating object histogram
    roihist = cv2.calcHist([hsv],[0, 1], None, [180, 256], [0, 180, 0, 256] )
    # normalize histogram and apply backprojection
    # 归一化：原始图像，结果图像，映射到结果图像中的最小值，最大值，归一化类型
    #cv2.NORM_MINMAX 对数组的所有值进行转化，使它们线性映射到最小值和最大值之间
    # 归一化之后的直方图便于显示，归一化之后就成了 0 到 255 之间的数了。
    cv2.normalize(roihist,roihist,0,255,cv2.NORM_MINMAX)
    dst = cv2.calcBackProject([hsvt],[0,1],roihist,[0,180,0,256],1)

    # Now convolute with circular disc
    # 此处卷积可以把分散的点连在一起
    disc = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
    dst=cv2.filter2D(dst,-1,disc)
    # threshold and binary AND
    ret,thresh = cv2.threshold(dst,50,255,0)
    # 别忘了是三通道图像，因此这里使用 merge 变成 3 通道
    thresh = cv2.merge((thresh,thresh,thresh))
    # 按位操作
    res = cv2.bitwise_and(target,thresh)
    res = np.hstack((target,thresh,res))
    cv2.imwrite('res.jpg',res)
    # 显示图像
    cv2.imshow('1',res)
    cv2.waitKey(0)

def hsvToBGR():
    nSz = 32
    img = np.zeros((nSz,nSz,3), np.uint8)

    #lower_blue = np.array([110,50,50])
    #upper_blue = np.array([130,255,255])
    for i in range(0,nSz):
        for j in range(0,nSz):
            if i < nSz/2:
                #img[i,j]=[0,60,32]
                #img[i,j]=[60,255,255]
                #img[i,j]=[0,255,255]
                img[i,j]=[110,200,200]
            else:
                #img[i,j]=[180,255,255]
                #img[i,j]=[0,0,255]
                img[i,j]=[130,255,255]
    img2 = cv2.cvtColor(img,cv2.COLOR_HSV2BGR)
    #img2 = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
    print img2

    cv2.imshow("img", img2)
    cv2.waitKey(0)

def testRoi():
    image = cv2.imread("c.jpg")
    image = image[0:100,100:300]
    cv2.imwrite("1.png",image)

if __name__ == '__main__':
    #myplot()
    #ROI()
    #colorChg()
    #traceBlue()
    #resize()
    #move()
    #rotate()
    #affineTransform()
    #perspectiveTransform()
    #pyramid()
    #grabcut()
    #PatternMatching()
    #picDraw()
    #calcHist()
    #backproject()
    #backproject2()
    #hsvToBGR()
    testRoi()
    cv2.destroyAllWindows()
    print "Exit!!!!"
